import React, { Component } from 'react'
import { Carousel } from 'antd-mobile'
import { arrayOf, shape, number, string, func } from 'prop-types'
import './style.scss'

class Swiper extends Component {
  render() {
    const { items, onClick } = this.props
    return (
      <Carousel autoplay={false} infinite className='myswiper'>
        {items.map(({ id, title, img }) => (
          <div key={id} className='swiper-list-item' onClick={e => onClick(id, e)}>
            <img
              src={img}
              alt={title}
              title={title}
              onLoad={() => {
                // 异步数据，图片默认开始时没有占满，所以需要触发resize事件重新计算一下
                window.dispatchEvent(new Event('resize'))
              }}
            />
          </div>
        ))}
      </Carousel>
    )
  }
}

// 限制属性类型
Swiper.propTypes = {
  items: arrayOf(
    shape({
      id: number.isRequired,
      img: string.isRequired,
      title: string.isRequired
    })
  ).isRequired,
  onClick: func
}

// 默认值
Swiper.defaultProps = {
  onClick: () => {}
}

export default Swiper
